package net.jiastudy.biz.sys.util;

import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.jiastudy.biz.sys.entity.Menu;
import net.jiastudy.biz.sys.entity.MenuRoot;

public class ReaderMenuConfig {

	private static final Logger logger = LoggerFactory.getLogger(ReaderMenuConfig.class);

	public static MenuRoot readerConfig() {
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					ReaderPermissionConfig.class.getResourceAsStream("/config/menuConfig.xml"), "UTF-8");
			JAXBContext jaxbContext = JAXBContext.newInstance(MenuRoot.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			MenuRoot permissionConfig = (MenuRoot) jaxbUnmarshaller.unmarshal(inputStreamReader);
			return permissionConfig;
		} catch (Exception e) {
			logger.error("读取权限配置出错：" + e);
			e.printStackTrace();
			return null;
		}
	}

	public static List<Menu> loadMenus(Set<String> permissions) {
		List<Menu> menus = ReaderMenuConfig.readerConfig().getMenus();
		return filterMenu(menus, permissions);
	}

	private static List<Menu> filterMenu(List<Menu> menus, Set<String> permissions) {
		if (null == menus) {
			return null;
		}
		Iterator<Menu> i = menus.iterator();
		while (i.hasNext()) {
			Menu menu = i.next();
			if (permissions.contains(menu.getPermission())) {
				filterMenu(menu.getItems(), permissions);
			} else {
				i.remove();
			}
		}
		return menus;
	}
}
